package com.tulei.api.ocr;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tulei.common.json.Json;
import okhttp3.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.json.JSONObject;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

import static com.tulei.common.json.Json.unmarshal;

/**
 * @Author TuLei
 * @Date 2024-05-17 12:31
 **/

public class BaiduImages {

    public static final String API_KEY = "IFZ3n6G5Kaa5407w1xAWEedb";
    public static final String SECRET_KEY = "hGJWdpwgVVyBwQA08S3rSdGGME9LM2wE";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    private static HashMap<String, TableCellBody> map = new HashMap<>();

    public static void main(String []args) throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String image = getFileContentAsBase64("D:\\Temp\\111.png",true); //方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        RequestBody body = RequestBody.create(mediaType, "image=" + image + "&cell_contents=false&return_excel=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/table?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        ResponseBody body1 = response.body();

        ObjectMapper objectMapper = new ObjectMapper();
        assert body1 != null;

        TableData tableData = null;
        try {
            tableData = Json.unmarshal(body1.string(), TableData.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Table table = tableData.getTablesResult().get(0);
        List<TableCellBody> tableCells = table.getBody();
        Optional<Integer> width = tableCells.stream().map(TableCellBody::getColEnd).max(Comparator.naturalOrder());
        Optional<Integer> length = tableCells.stream().map(TableCellBody::getRowEnd).max(Comparator.naturalOrder());
        for (TableCellBody tableCell : tableCells) {
            map.put(tableCell.getRowStart() + "" + tableCell.getColStart(), tableCell);
        }
        generateWord(map, width.orElse(0), length.orElse(0));
    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }


    public static void generateWord(HashMap<String, TableCellBody> map,int width,int length){
        String outpath = "D:\\Temp\\图片提取2.docx";
        XWPFDocument document = new XWPFDocument();
        FileOutputStream out;
        try {
            out = new FileOutputStream(outpath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        XWPFTable xwpfTable = document.createTable(width,length);
        for (int i = 0; i < length; i++) {
            XWPFTableRow xwpfRow = xwpfTable.getRow(i);
            while (xwpfRow.getTableCells().size() < width) {
                xwpfRow.createCell();
            }
            for (int j = 0; j < width; j++) {
                XWPFTableCell cell = xwpfRow.getCell(j);
                if (map.containsKey(i + "" + j)){
                    cell.setText(map.get(i + "" + j).getWords());
                }
            }
        }
        for (Map.Entry<String, TableCellBody> entry : map.entrySet()){
            TableCellBody value = entry.getValue();
            if (value.getRowEnd() - value.getRowStart() > 1 || value.getColEnd() - value.getColStart() > 1){
                mergeCells(xwpfTable,value.getRowStart(),value.getColStart(),value.getRowEnd() -1 ,value.getColEnd() -1);
            }
        }

        map.clear();
        try {
            document.write(out);
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }



    private static void mergeCells(XWPFTable table, int startRow, int startCol, int endRow, int endCol) {
        for (int rowNum = startRow; rowNum <= endRow; rowNum++) {
            for (int colNum = startCol; colNum <= endCol; colNum++) {
                XWPFTableCell cell = table.getRow(rowNum).getCell(colNum);
                if (rowNum == startRow && colNum == startCol) {
                    // 设置起始单元格的合并范围
                    cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                } else {
                    // 设置其他单元格的合并范围
                    cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                    cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                }
            }
        }
    }
}
